﻿//  <script src="http://webapi.amap.com/maps?v=1.3&key=@(Configs.GetValue("AMAP_JS_API_KEY"))&plugin=AMap.PolyEditor,AMap.CircleEditor"></script>
//  <script src="http://cache.amap.com/lbs/static/addToolbar.js"></script>
//  <script src="~/Content/js/amap/amap-edit-line-points.js"></script>
//$("#locMap").editLinePoints({

var LinePointsEditor = {
    options: {
        locInputId: undefined,//保存线路轨迹的控件编号
        locPoints: null,//站点序列，直接由locInputId的JSON反序列化生成
        markers: [],//站点
        //polyLine: null,
        onSelectMarker: undefined,//点击站点marker的回调函数
        zoom: 13 //地图显示的缩放级别
    },
    init: function (config) {
        var opts = $.extend(this.options, config);
        //获取线路数据
        var locStr = $("#" + opts.locInputId).val();
        var locJson = JSON.parse(locStr);
        if (locJson == null) {
            $("#" + opts.mapId).html("初始数据不存在或格式错误，无法编辑");
            return;
        }
        opts.locPoints = locJson.LocPoints;
        //声明地图
        opts.map = new AMap.Map($("#" + opts.mapId).attr("id"), {
            resizeEnable: true,
            zoom: 13 //地图显示的缩放级别
        });
        this.drawLines();
        this.drawPoints();
        //缩放地图
        opts.map.setFitView();
    },

    //初始化折线编辑器
    drawLines: function (onlymovelines) {
        var opts = this.options;
        var $this = this;
        //若移动站点Marker
        if (typeof onlymovelines != "undefined" && onlymovelines) {
            setTimeout(function () {
                var lineArry0 = $this.getLineArray();
                opts.editor._line.setPath(lineArry0);
            }, 200);
            return;
        }

        //生成编辑器
        var lineArry = this.getLineArray();
        var editor = {};
        opts.editor = editor;
        editor._line = (function () {
            return new AMap.Polyline({
                map: opts.map,
                path: lineArry,
                strokeColor: "#FF33FF",//线颜色
                strokeOpacity: 1,//线透明度
                strokeWeight: 6,//线宽
                strokeStyle: "solid",//线样式
                showDir: true
            });
        })();
        editor._lineEditor = new AMap.PolyEditor(opts.map, editor._line);
        editor.startEditLine = function () {
            editor._lineEditor.open();
        }
        editor.closeEditLine = function () {
            editor._lineEditor.close();
        }
        //editor._lineEditor.open();

        //增加点
        editor._lineEditor.on("addnode", function (e) {
            var mp = [e.lnglat.lng, e.lnglat.lat];
            updateLocation(1, mp);
        });

        //移动点
        editor._lineEditor.on("adjust", function (e) {
            var path = editor._line.getPath();
            var pathP = getArryFromPath(path);
            var oldLineArray = $this.getLineArray();
            var mps = getMovedPoint(oldLineArray, pathP);
            var stopArr = $this.getStopArray();
            var isStop = isPointInArray(mps[0], stopArr);
            if (isStop) {
                editor._line.setPath(oldLineArray);
                opts.lineArr = getArryFromPath(editor._line.getPath());
                return;
            }
            updateLocation(2, mps[0], mps[1]);
        });

        //删除点
        editor._lineEditor.on("removenode", function (e) {
            var mp = [e.lnglat.lng, e.lnglat.lat];
            var stopArr = $this.getStopArray();
            var isStop = isPointInArray(mp, stopArr);
            if (isStop) {
                setTimeout(function () {
                    var oldLineArray = $this.getLineArray();
                    editor._line.setPath(oldLineArray);
                    opts.lineArr = getArryFromPath(editor._line.getPath());
                }, 100);
                return;
            }
            updateLocation(3, mp);
        });

        //编辑状态开关按钮
        var html = '' +
    '            <div class="button-group" style="bottom:30px;">' +
    '                <input id="beginEditLien" type="button" class="button" value="开始编辑路线" />' +
    '                <input id="endEditLien" type="button" class="button" value="结束编辑路线" />' +
    '            </div>';
        $("#" + opts.mapId).parent().append(html);
        $("#beginEditLien").click(function () {
            editor.startEditLine();
        });
        $("#endEditLien").click(function () {
            editor.closeEditLine();
        });

        //修改路径
        function updateLocation(type, p1, p2) {
            if (type == 1) {//新增
                var path = editor._line.getPath();
                var pathP = getArryFromPath(path);
                for (var i = 0; i < pathP.length; i++) {
                    if (checkPosition(pathP[i], p1)) {
                        opts.locPoints.splice(i, 0, {
                            Lng: p1[0],
                            Lat: p1[1],
                            IsStop: false,
                            Position: 0
                        });
                        break;
                    }
                }
            } else if (type == 2) {//移动
                for (var i = 0; i < opts.locPoints.length; i++) {
                    var lp = opts.locPoints[i];
                    if (checkPosition([lp.Lng, lp.Lat], p1)) {
                        lp.Lng = p2[0];
                        lp.Lat = p2[1];
                        break;
                    }
                }
            } else if (type == 3) {//删除 splice
                for (var i = 0; i < opts.locPoints.length; i++) {
                    var lp = opts.locPoints[i];
                    if (checkPosition([lp.Lng, lp.Lat], p1)) {
                        opts.locPoints.splice(i, 1);
                        break;
                    }
                }
            }

            $this.resetInputValue();
        };

        //根据ampa的path获取位置数组
        function getArryFromPath(path) {
            var list = [];
            for (var i = 0; i < path.length; i++) {
                var p = path[i];
                var p1 = [p.lng, p.lat];
                list.push(p1);
            }
            return list;
        };

        //比较两个位置数组，找到移动了位置
        function getMovedPoint(oldArry, arry) {
            for (var i = 0; i < arry.length; i++) {
                var p = arry[i];
                var oldP = oldArry[i];
                if (!checkPosition(p, oldP)) {
                    return [oldP, p];
                }
            }
            return null;
        };

        //判断两个位置是否相同
        function checkPosition(p1, p2) {
            return p1[0] == p2[0] && p1[1] == p2[1];
        };

        //判断点p是否在arry中
        function isPointInArray(p, arry) {
            for (var i = 0; i < arry.length; i++) {
                var ap = arry[i];
                if (checkPosition(p, ap)) {
                    return true;
                }
            }
            return false;
        };

    },

    //绘制Marker点
    drawPoints: function () {
        var opts = this.options;
        //标注点
        for (var i = 0; i < opts.locPoints.length; i++) {
            var locPoint = opts.locPoints[i];
            if (locPoint.IsStop) {
                var marker = this.drawPoint(locPoint);
                opts.markers.splice(locPoint.Position - 1, 0, marker);
            }
        }
    },

    //增加站点
    drawPoint: function (locPoint) {
        var opts = this.options;
        $this = this;
        var marker = new AMap.Marker({
            icon: "http://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
            position: [locPoint.Lng, locPoint.Lat],
            label: {
                offset: new AMap.Pixel(24, 6),
                content: locPoint.Position + ". " + locPoint.StopName + ""
            }
        });
        marker.setMap(opts.map);
        marker.stopName = locPoint.StopName;
        marker.stopPosition = locPoint.Position;
        AMap.event.addListener(marker, 'dragging', function () {
            var stopPosition = this.stopPosition;
            var stopName = this.stopName;
            var position = this.getPosition();
            $this.moveStopPoint(stopPosition, position);
        });
        AMap.event.addListener(marker, 'dragend', function () {
            var stopPosition = this.stopPosition;
            var stopName = this.stopName;
            var position = this.getPosition();
            $this.moveStopPoint(stopPosition, position);
            if (!!opts.markerDragend) {
                opts.markerDragend(stopPosition, position.lng, position.lat);
            }
        });
        AMap.event.addListener(marker, 'click', function () {
            var stopPosition = this.stopPosition;
            $this.selectMarker(stopPosition);
        });
        return marker;
    },

    //获取折线线段集合
    getLineArray: function () {
        var opts = this.options;
        var lineArr = [];//线路所有点集合
        for (var i = 0; i < opts.locPoints.length; i++) {
            var lp = opts.locPoints[i];
            lineArr.push([lp.Lng, lp.Lat]);
        }
        return lineArr;
    },

    //移动站点
    moveStopPoint: function (position, loc) {
        var opts = this.options;
        var p = 0;
        for (var i = 0; i < opts.locPoints.length; i++) {
            var lp = opts.locPoints[i];
            if (lp.IsStop) {
                if (++p == position) {
                    lp.Lng = loc.lng;
                    lp.Lat = loc.lat;
                    break;
                }
            }
        }
        var lineArry = this.getLineArray();
        opts.editor._line.setPath(lineArry);

        this.resetInputValue();
    },

    //获取所有站点集合
    getStopArray: function () {
        var opts = this.options;
        var stopArr = [];
        for (var i = 0; i < opts.locPoints.length; i++) {
            var lp = opts.locPoints[i];
            if (lp.IsStop) {
                stopArr.push([lp.Lng, lp.Lat]);
            }
        }
        return stopArr;
    },

    //选择marker
    selectMarker: function (position) {
        var opts = this.options;
        for (var i = 0; i < opts.markers.length; i++) {
            var marker = opts.markers[i];
            if (i == position - 1) {
                marker.setIcon("http://webapi.amap.com/theme/v1.3/markers/n/mark_r.png");
                marker.setDraggable(true);
                if (opts.onSelectMarker) {
                    for (var j = 0; j < opts.locPoints.length; j++) {
                        var lp = opts.locPoints[j];
                        if (lp.IsStop && lp.Position == position) {
                            opts.onSelectMarker(lp);
                            break;
                        }
                    }
                }
            } else {
                marker.setIcon("http://webapi.amap.com/theme/v1.3/markers/n/mark_b.png");
                marker.setDraggable(false);
            }
            //修复高德js bug
            marker.setTitle(marker.getTitle());
        }
    },

    //新增站点
    addMarker: function (locPoint) {
        var opts = this.options;
        var position = locPoint.Position;
        for (var i = 0; i < opts.locPoints.length; i++) {
            var lp = opts.locPoints[i];
            if (lp.IsStop) {
                if (lp.Position == position) {
                    //在lp的位置插入marker
                    var lpPre;
                    if (i == opts.locPoints.length - 1) {
                        lpPre = { Lng: lp.Lng + 0.0001, Lat: lp.Lat + 0.0001, };
                    } else {
                        lpPre = opts.locPoints[i - 1];
                    }
                    locPoint.Lng = (lp.Lng + lpPre.Lng) / 2;
                    locPoint.Lat = (lp.Lat + lpPre.Lat) / 2;
                    opts.locPoints.splice(i, 0, locPoint);

                    var marker = this.drawPoint(locPoint);
                    opts.markers.splice(position - 1, 0, marker);
                    //改变原lp信息
                    lp.Position++;
                    resetMarkerTitle(lp);
                    i++;
                    continue;
                }
                if (lp.Position > position) {
                    lp.Position++;
                    resetMarkerTitle(lp);
                }
            }
        }
        this.drawLines(true);
        this.resetInputValue();
        this.selectMarker(position);

        function resetMarkerTitle(lp) {
            var mk = opts.markers[lp.Position - 1];
            mk.stopName = lp.StopName;
            mk.stopPosition = lp.Position;
            opts.markers[lp.Position - 1].setTitle(lp.Position + ". " + lp.StopName + "");
        }
    },

    //删除站点
    deleteMarker: function (position) {
        var opts = this.options;
        for (var i = 0; i < opts.locPoints.length; i++) {
            var lp = opts.locPoints[i];
            if (lp.IsStop) {
                if (lp.Position == position) {
                    //移除marker
                    var marker = opts.markers[position - 1];
                    marker.setMap(null);
                    opts.markers.splice(position - 1, 1);
                    opts.locPoints.splice(i, 1);
                    i--;
                    continue;
                }
                if (lp.Position > position) {
                    lp.Position--;
                    var mk = opts.markers[lp.Position - 1];
                    mk.stopName = lp.StopName;
                    mk.stopPosition = lp.Position;
                    mk.setTitle(lp.Position + ". " + lp.StopName + "");
                }
            }
        }
        this.drawLines(true);
        this.resetInputValue();
    },

    //修改INPUT控件的值
    resetInputValue: function () {
        var opts = this.options;
        var json = JSON.parse($("#" + opts.locInputId).val());
        json.LocPoints = opts.locPoints;
        $("#" + opts.locInputId).val(JSON.stringify(json));
    }
}
